from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import  JSONResponse
from fastapi.templating import Jinja2Templates

# 初始化新的日志系统 - 在其他导入之前
from config.logging_config import init_logging, ProjectLoggers
init_logging()

from database.MysqlUtils import async_engine
from mrouter.domain.WxCloudRunHeader import WxCloudRunHeader
from utils import QiniuHelper
from config.qiniu_config import QINIU_CONFIG
# 导入所有路由
from mrouter.qiniu_router import router as qiniu_router
from mrouter.user_router import router as user_router
from mrouter.video_router import router as video_router
from mrouter.youtube_router import router as youtube_router
from mrouter.facebook_router import router as facebook_router
from mrouter.instagram_router import router as instagram_router
from mrouter.twitter_router import router as twitter_router
from mrouter.universal_router import router as universal_router
from mrouter.hls_router import router as hls_router


# 获取主应用日志记录器
logger = ProjectLoggers.get_main_logger()

# 生命周期管理
@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("🚀 xiongmao-parse-mp3应用正在启动...")
    
    # 初始化Redis
    # await init_redis()
    
    # 初始化七牛云
    logger.info("☁️ 正在初始化七牛云配置...")
    QiniuHelper.init(
        access_key=QINIU_CONFIG['access_key'],
        secret_key=QINIU_CONFIG['secret_key'],
        bucket_name=QINIU_CONFIG['bucket_name']
    )
    if QINIU_CONFIG['domain']:
        QiniuHelper.set_domain(QINIU_CONFIG['domain'])
    logger.info("✅ 七牛云配置初始化完成")
    
    # 检查FFmpeg是否可用
    from utils.ffmpeg_helper import FFmpegHelper
    if FFmpegHelper.check_ffmpeg_available():
        logger.info("✅ FFmpeg检查通过，视频转音频功能可用")
    else:
        logger.warning("⚠️ FFmpeg不可用，视频转音频功能将无法正常工作")
    
    # 数据库表需要手动创建，请执行 database/mysql/video_tasks_table.sql 脚本
    logger.info("📊 请确保数据库表已手动创建（执行 database/mysql/video_tasks_table.sql）")
    
    # 启动后台任务服务
    from service.task_service import task_service
    await task_service.start_background_service()

    logger.info("🎯 应用启动完成，开始处理请求")
    yield
    
    # 关闭资源
    logger.info("🔄 正在关闭应用资源...")
    
    # 停止后台任务服务
    await task_service.stop_background_service()
    
    await async_engine.dispose()
    # await redis_pool.close()
    logger.info("✅ 应用资源关闭完成")

# 创建FastAPI应用实例，禁用Swagger文档
app = FastAPI(
    title="熊猫视频转mp3",
    description="熊猫视频转mp3",
    version="1.0.0",
    lifespan=lifespan,
    docs_url=None,  # 禁用Swagger UI (/docs)
    redoc_url=None  # 禁用ReDoc (/redoc)
)

# 注册所有路由
app.include_router(qiniu_router)
app.include_router(user_router)
app.include_router(video_router)
app.include_router(youtube_router)
app.include_router(facebook_router)
app.include_router(instagram_router)
app.include_router(twitter_router)
app.include_router(universal_router)
app.include_router(hls_router)

templates = Jinja2Templates(directory="templates")


@app.get("/video/getOpenId")
async def getOpenId(request: Request):
    try:
        openid = await WxCloudRunHeader.get_openid(request)
        return {"code": 200, "msg": "成功", "data": openid}
    except Exception as err:
        logger.error(f"获取OpenId失败: {err}")
        return {
            "code": 500,
            "msg": str(err),
        }

# 微信云托管请求头信息获取演示接口 - 保留此处代码
@app.get("/wechat/cloudrun/header")
async def get_cloudrun_header_info(request: Request):
    """
    获取微信云托管请求头信息的演示接口
    """
    try:
        # 使用WxCloudRunHeader类获取信息
        openid = await WxCloudRunHeader.get_openid(request)
        appid = await WxCloudRunHeader.get_appid(request)
        unionid = await WxCloudRunHeader.get_unionid(request)
        env_id = await WxCloudRunHeader.get_env_id(request)
        source = await WxCloudRunHeader.get_source(request)
        client_ip = await WxCloudRunHeader.get_client_ip(request)
        is_from_wx = await WxCloudRunHeader.is_from_wx_ecosystem(request)
        
        # 获取环境变量信息
        current_env_id = WxCloudRunHeader.get_current_env_id()
        mysql_config = WxCloudRunHeader.get_mysql_config()
        
        # 记录请求信息到日志
        await WxCloudRunHeader.log_request_info(request)
        
        # 返回综合信息
        return JSONResponse(content={
            "code": 200, 
            "msg": "获取成功",
            "data": {
                "request_headers": {
                    "openid": openid,
                    "appid": appid,
                    "unionid": unionid,
                    "env_id": env_id,
                    "source": source,
                    "client_ip": client_ip,
                    "is_from_wx_ecosystem": is_from_wx
                },
                "environment_variables": {
                    "current_env_id": current_env_id,
                    "mysql_config": {
                        "username": mysql_config.get("username"),
                        "address": mysql_config.get("address"),
                        "password": "******" if mysql_config.get("password") else None
                    }
                }
            }
        })
    except Exception as e:
        logger.error(f"获取云托管请求头信息失败: {str(e)}")
        return JSONResponse(
            status_code=500,
            content={"code": 500, "msg": f"获取云托管请求头信息失败: {str(e)}"}
        )

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
